#!/bin/bash
# description: Auto create myrepo by yum and createrepo
# version: 0.0.1
# author: Chuck<zhangchiqian@foxmail.com>
# date: 2021-1-19

PKG_NAME=$1
REPO_PATH="/mydata/rpmrepo"

if [ $# -eq 0 ];then
   createrepo --update -v $REPO_PATH
   exit 0
elif [ $# -ne 1 ];then
   echo "the number of  parameters error " >&2
   exit 3  
fi  
echo "+------------------------------------------+"
echo "|   Start to download ${PKG_NAME}           "
echo "+------------------------------------------+"
#yum clean expire-cache && yum makecache
if EXIST=$(ls -1 ${REPO_PATH}|grep -i '^'${PKG_NAME} 2>/dev/null);then
	echo "These packages already exist:"
	for i in $EXIST;do
		echo -e "\033[31;1m "$i" \033[0m"
	done
	echo "These packages is available from the yum repo:"
	PKG_LIST=$(yum list all --showduplicates| grep -i '^'${PKG_NAME})
	declare -a PKG_ARRAY
	oldIFS=$IFS
	IFS=$'\n'
	declare -i j=1
	for i in $PKG_LIST;do
        	PKG_ARRAY[j]=$i
        	echo "(${j}) ${i}"
        	let j++ 
	done
	IFS=$oldIFS
	read -p "Are you still want to download ${PKG_NAME}?(y/n)" CHOICE
	[[ ${CHOICE,,} == @(+(y)|ye|yes) ]] || exit 0
	read -p "Enter the serial number of the specific package:" SERIAL
	if [ -z ${PKG_ARRAY[SERIAL]} ];then
		exit 0
	fi
	PKG=$(echo ${PKG_ARRAY[SERIAL]}|sed -r 's@\s*([^.]+)(\.\S+)\s+(\S+).*@\1-\3\2@')
	echo $PKG
	yumdownloader --destdir=$REPO_PATH ${PKG}  
else
	#加--resolve表示下载rpm包的同时下载依赖
	yumdownloader --destdir=$REPO_PATH --resolve ${PKG_NAME} 
fi
#如果yum install成功则执行createrepo
if [ $? -eq 0 ];then
	chown nginx.nginx  ${REPO_PATH}/*.rpm
	createrepo --update -v $REPO_PATH
fi
